import { PageContainer } from '@ant-design/pro-layout';
import React, {useRef, useState} from 'react';
import { EditableProTable, ProColumns } from '@ant-design/pro-table';
import ProTable, { ActionType } from '@ant-design/pro-table';
import request from '@/utils/request';
import { Button, InputNumber, message, Spin, Upload } from 'antd';
import { manufacturerOption, newUUID } from '@/utils/utils';
import { DrawerForm, ProFormDatePicker, ProFormGroup, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import ProductChoose from './ProductChoose';
import Popconfirm from 'antd/es/popconfirm';

import { Modal } from 'antd';
import CustomerChoose from './CustomerChoose';

const { confirm } = Modal;

export type PutOutProps = {
  admin:boolean;
};

const SaleReport: React.FC<PutOutProps> = (props)=>{
  const formRef = useRef<any>();

  const actionRef = useRef<ActionType>();
  const [proModalVisible, setProModalVisible] = useState(false);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [ticketAttList,setTicketAttList]= useState([]);
  const [showDetail, setShowDetail] = useState(false);
  const [spinningFlag,setSpinningFlag]  = useState(false);
  const [detailFlag,setDetailFlag]  = useState(false);
  const [custModalVisible,setCustModalVisible] = useState<boolean>(false);
  const [dealerData,setDealerData] = useState([]);
  const [proData,setProData] = useState([]);
  const [pIndex,setPindex]  = useState<number>(0);
  const [shipId,setShipId] = useState("");
  const [activeKey,setActiveKey] = useState("tab1");
  const [detailData,setDetailData] =useState<any>({});
  const [hospitalData,setHospitalData] = useState<any>({});
  
  const admin = sessionStorage.getItem("access").indexOf('admin')>=0;
  const problemList =(params:any)=>{
    var data =  request('/xwyl/problem/problemList', {     method: 'POST',params:{...params}});
    return data;
  }

  const findProblem =(params:any)=>{
    var data =  request('/xwyl/problem/findProblem', {     method: 'POST',params:{...params}});
    return data;
  }

  const hospitalDataById =(params:any)=>{
    var data =  request('/xwyl/hospital/hospitalDataById', { method: 'POST',params:{...params}});
    return data;
  }

  const fileData =(param:any)=>request('/xwyl/attachment/attachListData',{
    method: 'POST',
    requestType:'form',
    data: {
      ...param,
    },
  });

  const addProblem = (params:any)=>{
   return request('/xwyl/problem/addProblem', {
        method: 'POST',
        headers:{
          'Content-Type': 'application/json',
          'authorization':`${sessionStorage.getItem('token')}`
        },
        data: {
          ...params,
          method: 'post',
        },
      });
  }

  // const dealerJsonData=async()=> {
  //   var val = await request('/xwyl/dealer/getMyDealers');
  //   if(val.errorCode==='200'){
  //     val.data.forEach((element:any) => {
  //       element.label = element.cnName;
  //       element.value = element.id;
  //     });
  //     setDealerData(val.data.map((item:any)=>{
  //         return {label:item.label,value:item.value}
  //     }));
  //   }
  // }

  
 const chooseCustomer: ProColumns[] = [
  {
    title:'医院编码',
    dataIndex: 'bh',
    width: 100
  },
  {
    title:"医院名称",
    dataIndex: 'customerName',
  },
  {
    title: '操作',
    valueType: 'option',
    width: 100,
    render: (text, record:any,_, action) => {
      return [<a onClick={async()=>{
        var val = await  hospitalDataById({id:record.customerId})
        if(val.errorCode==='200'){
          if(val.data.dealerList&&val.data.dealerList.length>0){
            setHospitalData(record)
            formRef.current.setFieldsValue({"hospital_name":record.customerName});
            formRef.current.setFieldsValue({"dealer_id":''});
            setDealerData(val.data.dealerList.map((item:any)=>{
                return {label:item.cnName,value:item.id}
            }));
            if(val.data.dealerList.length===1){
              formRef.current.setFieldsValue({"dealer_id":val.data.dealerList[0].id});
            }else{
              formRef.current.setFieldsValue({"dealer_id":''});
            }
          }else{
            message.error('该医院暂未绑定客户，请联系管理员')
          }
        }else{
          message.error('获取客户数据失败，请重试！')
          formRef.current.setFieldsValue({"dealer_id":''});
          setDealerData([]);
        }
        setCustModalVisible(false)
      }}>选择</a>]
    }
  }

];

  const custData = (params:any)=>{
    var data = request('/xwyl/salesTeam/salesCustomerData',{params});
    return data;
  }

  const uploadProps = {
    multiple: false,
    name: 'file',
    accept:'image/*,application/pdf',
    action: '/xwyl/attachment/uploadAttach',
    headers: {
      authorization: 'authorization-text',
    },
    beforeUpload:(file: any, FileList: any[])=>{
      var flag =  file.type.indexOf('image/')>=0||file.type.indexOf('pdf')>=0;
      if(!flag){
         message.error('请上传图片格式或pdf格式')
      }
      return flag;
    }
  };

  const handlePreview = async (file:any) => {
    window.open(file.url);
   };

    //表头信息以及表值设置
    const columns: ProColumns[] = [
        {
          title: '客户代码',
          dataIndex: 'dealerCode',
          width: 150,
        },
        {
          title: '客户名称',
          dataIndex: 'dealerName',
          width: 200,
          ellipsis:true
        },
        {
          title:'医院编码',
          dataIndex: 'hospital_bh',
          width: 100
        },
        {
          title:"医院名称",
          dataIndex: 'hospital_name',
          width: 200,
          ellipsis:true
        },
        {
            title: '异常月份',
            dataIndex: 'abnormal_month',
            width: 100,
            hideInSearch:true,
        },
        {
          title: '提交人',
          dataIndex: 'salesName',
          width: 100,
          hideInSearch:true
      },
        {
            title: '提交日期',
            dataIndex: 'date',
            valueType:'dateRange',
            width: 100,
            hideInTable:true
        },
        {
            title: '发票号码',
            dataIndex: 'bill_number',
            width: 100,
        },
        {
            title: '出库单号',
            dataIndex: 'put_out_no',
            hideInSearch:true,
            width: 100,
        },
        {
            title: '提交日期',
            dataIndex: 'submission_time',
            hideInSearch:true,
            width: 100,
        },
        {
            title: '操作',
            valueType: 'option',
            width: 100,
            render: (text, record,_, action) => {
              return [<a key="detail" onClick={async()=>{
                    var val = await findProblem({id:record.id})
                    if(val.errorCode==='200'){
                        var index=0;
                        val.data.productList.forEach((item:any) => {
                            item.pIndex = index;
                            index++
                        });
                        setShipId(record.id)
                        setEditableRowKeys([])
                        setProData(val.data.productList);
                        setDetailFlag(true)
                        setDetailData(val.data)
                        setShowDetail(true)
                        var param:any={"shipId":record.id};
                        var val =await fileData(param)
                        if(val.errorCode="200"){
                          val.data.forEach((element:any) => {
                            element.uid=element.id;
                            element.name=element.attName;
                            element.url=element.attPath;
                            element.status='done';
                          });
                          setTicketAttList(val.data);
                        }
                    }else{
                        message.error(val.errorMessage);
                    }
                }}>详情</a>,<Popconfirm  title="确定作废该医院吗?"     key="delete" onConfirm={async() => {
                    var param = {id:record.id,audit_status:3}
                    var val = await addProblem(param);
                    if(val.errorCode==='200'){
                        message.success('作废成功');
                        actionRef.current?.reloadAndRest?.();
                    }else{
                        message.error(val.errorMessage);
                    }
                }}>
                <a key="remove" hidden={admin||record.audit_status!='1'}>作废</a>
              </Popconfirm>
            ,
            ]
            },
          },
    ]

    React.useEffect(()=>{
            // dealerJsonData()
            return function cleanup() {
        };
    },[]);

    const outColumns: ProColumns[] = [
        {
          title: '厂家',
          dataIndex: 'manufacturer',
          valueType:'select',
          hideInTable:true,
          valueEnum:manufacturerOption(),
          width:80,
          editable:false,
        },
        {
          title: '产品名称',
          dataIndex: 'product_name',
          editable:false,
        },
        {
          title: '产品型号',
          dataIndex: 'product_standard',
          editable:false,
        },
        {
          title: '单位',
          dataIndex: 'packing_unit',
          editable:false,
          hideInTable:true,
        },
        {
            width:100,
            title: '系统销量',
            dataIndex: 'systemSales',
            formItemProps: (form, { rowIndex }) => {
              return {
                rules: [{ required: true, message: '系统销量必填' }]
              };
            },
            renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
              return <InputNumber {...fieldProps} placeholder="请输入" precision={0} min={0}/>;
            },
          },
        {
          width:100,
          title: '实际数量',
          dataIndex: 'actualSales',
          formItemProps: (form, { rowIndex }) => {
            return {
              rules: [{ required: true, message: '实际数量必填' }]
            };
          },
          renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
            return <InputNumber {...fieldProps} placeholder="请输入" precision={0} min={0}/>;
          },
        },
        {
          title: '操作',
          valueType: 'option',
          width: 100,
          render: () => {
            return null;
          },
        },
      ];


   return (
    <PageContainer>
      <ProTable
        headerTitle=''
        actionRef = {actionRef}
        columns={columns}
        scroll={{x:1000}}
        request={(params, sorter, filter) =>{
          if(params.date){
            params.beginDate=params.date[0];
            params.endDate=params.date[1];
            params.date=undefined;
          }
          if(activeKey==='tab1'){
            params.audit_status=1;
          }else{
            params.audit_status=2;
          }
          return problemList({...params,filter})
        }}
        rowKey="id"
        search={{
          span: 6,
          defaultCollapsed: false,
        }}
        toolBarRender={() => [
                <Button
                  hidden={admin}
                  type="primary"
                  key="primary"
                  onClick={() => {
                    setTicketAttList([])
                    setEditableRowKeys([])
                    setDetailFlag(false)
                    setDetailData({})
                    setShipId(newUUID())
                    setProData([])
                    setPindex(0)
                    setShowDetail(true)
                  }}
                >新增</Button>
        ]}
        toolbar={{settings:[],
            menu: {
                type: 'tab',
                activeKey: activeKey,
                items: [
                  {
                    key: 'tab1',
                    label: <span>待处理</span>,
                  },
                  {
                    key: 'tab2',
                    label: <span>已处理</span>,
                  },
                ],
                onChange: (key) => {
                  setActiveKey(key as string);
                  actionRef.current?.reloadAndRest?.();
                },
              },
        }}
        pagination={{
          pageSizeOptions:['20', '100', '500']
        }}
        />
      <DrawerForm
          width={1000}
          title="详情"
          visible={showDetail}
          formRef = {formRef}
          onVisibleChange={setShowDetail}
          onFinish={async (values: any) => {
            if(proData.length==0){
            message.warning("请先添加产品")
            return false;
            }
            if(values.bill_number.length!==8){
              message.warning("发票号码长度不正确")
              return false;
            }
            if(ticketAttList.length===0){
              message.warning("请先上传附件")
              return false;
            }
            values.id = shipId;
            if(admin){
                values.audit_status='2';
            }else{
                values.product=[];
                proData.forEach((item:any)=>{
                    // item.product_id = item.id;
                    values.product.push({"product_id":item.id,"product_name":item.product_name,"product_standard":item.product_standard,"systemSales":item.systemSales,'actualSales':item.actualSales})
                })
                values.audit_status='1';
            }

             values.hospital_id = hospitalData.customerId
             values.hospital_bh = hospitalData.bh
             var val =await addProblem(values);
             if(val.errorCode==='200'){
               message.success('提交成功');
               actionRef.current?.reloadAndRest?.();
               return true;
             }else{
               message.error(val.errorMessage);
               return false;
             }
          }}
          drawerProps={{
           forceRender: true,
           destroyOnClose: true,
         }}
         submitter={{
            searchConfig:{
                submitText:admin?"已处理":'提交',
                resetText:"取消"
             },

            render: (props, defaultDoms) => {
              return !admin&&detailFlag?[]:[
                ...defaultDoms,
              ];
            },
          }}
         >
             {detailFlag?
                <div style={{marginLeft:20}}>
                <ProFormGroup>
                    <ProFormText name="hospital_bh"  readonly={detailFlag} initialValue={detailData?.hospital_bh} hidden={!detailFlag} label="医院编码" width='md' />
                    <ProFormText name="hospital_name"  readonly={detailFlag} initialValue={detailData?.hospital_name} hidden={!detailFlag} label="医院名称" width='md' />
                </ProFormGroup>
                <ProFormGroup>
                    <ProFormText name="dealer_code"  readonly={detailFlag} initialValue={detailData?.dealerCode} hidden={!detailFlag} label="客户编码" width='md' />
                    <ProFormText name="dealer_id"  readonly={detailFlag} initialValue={detailData?.dealerName} hidden={!detailFlag} label="客户名称" width='md' />
                    <ProFormDatePicker.Month readonly={detailFlag} initialValue={detailData?.abnormal_month} label="异常月份" name="abnormal_month" width='md' />
                    <ProFormText name="bill_number" readonly={detailFlag} initialValue={detailData?.bill_number} label="发票号码" width='md'/>
                    <ProFormText name="put_out_no" readonly={detailFlag} initialValue={detailData?.put_out_no} label="出库单号" width='md' />
                </ProFormGroup>
                <ProFormTextArea name="problem_description" readonly={detailFlag} initialValue={detailData?.problem_description} label="申诉描述" fieldProps={{showCount:true,maxLength:500}}/>
                </div>:<>
                <div style={{alignItems:'start',display:'flex'}}>
                   <ProFormText name="hospital_name" width='md' label="" placeholder='请选择医院' disabled rules={[
                {
                    required: true,
                }]}/>
                   <Button type='primary' key="choose" style={{marginLeft:30}} onClick={()=>{
                      setCustModalVisible(true);
                   }}>选择医院</Button>
                </div>
                <ProFormGroup>
                {/* <ProFormText name="dealerName" width='md' label="客户" placeholder='' disabled /> */}

                <ProFormSelect name="dealer_id" label="客户" showSearch width='md' options={dealerData} rules={[
                {
                    required: true,
                },
                ]} fieldProps={{filterOption:(input, option:any) =>{
                        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    }}/>
                    <ProFormDatePicker.Month initialValue={detailData?.abnormal_month} label="异常月份" name="abnormal_month" width='md' rules={[{required: true}]}/>
                </ProFormGroup>
                <ProFormGroup>
                    <ProFormText name="bill_number" initialValue={detailData?.bill_number} label="发票号码" width='md' rules={[{required: true}]}/>
                    <ProFormText name="put_out_no"  initialValue={detailData?.put_out_no} label="出库单号" width='md'/>
                </ProFormGroup>
                <ProFormTextArea name="problem_description" initialValue={detailData?.problem_description} label="申诉描述" rules={[{required: true}]} fieldProps={{showCount:true,maxLength:500}}/>

                </>
            
            }
             <EditableProTable
              headerTitle="产品列表"
              rowKey="pIndex"
              columns={outColumns}
              value={proData}
              search={false}
              toolbar={{settings:[]}}
              recordCreatorProps={false}
              onChange={(data:any) => {
                setEditableRowKeys(data.map((item:any) => item.pIndex));
                setProData(data);
              }}
              toolBarRender={() => [
                <Button
                  type="primary"
                  key="primary"
                  hidden={admin||detailFlag}
                  onClick={() => {
                    setProModalVisible(true);
                  }}
                >
                  <PlusOutlined />添加
                </Button>,
              ]}
              pagination={false}
              editable={{
                editableKeys,
                type: 'multiple',
                onChange: setEditableRowKeys,
                onValuesChange: (record, recordList:any) => {
                  setProData(recordList);
                },
                actionRender: (row, config, defaultDoms) => {
                  return [defaultDoms.delete];
                },
              }}
           ></EditableProTable>
           <div style={{margin:20}}>
           <Upload  {...uploadProps} onPreview={handlePreview}  fileList={ticketAttList}
                onRemove={(record)=>{
                  confirm({
                    content: "确定删除吗？",
                    onOk:async()=> {
                      var req = request('/xwyl/attachment/deleteAtt', {
                        method: 'POST',
                        requestType:'form',
                        data: {
                        ...{"id":record.uid},
                        method: 'post',
                        },
                      });
                      var val =await req;
                      if(val.errorCode==='200'){
                          var newList=ticketAttList.filter((item:any)=>{
                          return item.uid!=record.uid;
                          });
                          setTicketAttList(newList);
                      }else{
                          message.error("删除失败");
                      }
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }}
                onChange={(info:any)=>{
                if (info.file.status === 'done') {
                    if(info.file.response.errorCode==="200"){
                    var list:any[] = ticketAttList;
                    message.success(`${info.file.name}上传成功`);
                    var data = info.file.response.data;
                    data.uid = data.attId;
                    data.name = info.file.name;
                    data.url = data.location;
                    data.status ='done';  
                    list.push(data);
                    setTicketAttList([...list]);
                    }else{
                    message.error(`${info.file.name} 上传失败.`);
                    }
                } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败.`);
                }
                }}   data={{'shipId':shipId,'userId':sessionStorage.getItem("userId")}} headers={{
                'authorization':`${sessionStorage.getItem('token')}`}}>
                <Button hidden={detailFlag}  icon={<UploadOutlined />}><span style={{color:'red'}}>*</span>上传发票</Button>
                </Upload>
           </div>
        
       </DrawerForm>
       <ProductChoose
            onCancel={() => {
              setProModalVisible(false);
            }}
            onSubmit={async (value:any[]) => {
              var mIndex=pIndex;
              value.forEach(v=>{
                v.pIndex=mIndex;
                v.numbs=0;
                v.systemSales = 0;
                v.actualSales = 0;
                mIndex++;
              })
              setPindex(mIndex);
              setProModalVisible(false);
              var data:any = [...proData,...value];
              setEditableRowKeys(data.map((item:any)=>item.pIndex));
              setProData(data);
            }}
             modalVisible={proModalVisible}
         />

      <CustomerChoose
              onCancel={() => {
                setCustModalVisible(false);
              }}
              single ={true}
              onSubmit={(value) => {
                setCustModalVisible(false);

              }}
              modalVisible={custModalVisible}
              columns={chooseCustomer}
              requestFunction={custData}
          />
      <Spin spinning={spinningFlag} style={{transform:'translate(-50%,-50%)',left:'50%',top:'50%',position:'absolute'}}/>
  </PageContainer>
  );
}


export default SaleReport;